import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/widgets/loading_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'view_state_widget.dart';

class NormalGridController {
  _SubCollectState? _inState;

  void refresh() {
    _inState?._scrollController.jumpTo(0);
    _inState?._controller.requestRefresh();
  }

  void animateTo(
    double offset, {
    Duration? duration,
    Curve? curve,
  }) {
    _inState?._scrollController.animateTo(0,
        duration: duration ?? Duration(milliseconds: 300),
        curve: curve ?? Curves.bounceInOut);
  }

  void reloadData() {
    _inState?._loadingGetData();
  }
}

int _defaultPageSize(page) => 15;

class NormalGridView<T> extends StatefulWidget {
  final int crossAxisCount;
  final Widget Function(BuildContext, T, int) itemBuilder; // 返回列表中每行Item
  final Widget Function(bool, String)? holder; // 空页面或者错误占位页面
  final EdgeInsets padding;
  final Future<List<T>> Function(int) getData; // 获取数据（接口函数）
  final int Function(int) pageSize; // 每页数据个数，默认10个
  final Widget Function(BuildContext)? header;
  final void Function(BuildContext context, double offset)? onScroll;
  final NormalGridController? controller;
  final StaggeredTile? Function(int index)? staggeredTileBuilder;
  final double mainAxisSpacing;
  final double crossAxisSpacing;
  final bool showNoData;
  // final Widget Function(BuildContext context, String text, RefreshStatus state)?
  //     refreshItemBuilder;
  final bool enableLoadMore;

  NormalGridView({
    required this.itemBuilder,
    this.holder,
    this.header,
    required this.getData,
    this.pageSize = _defaultPageSize,
    this.padding = EdgeInsets.zero,
    this.onScroll,
    this.crossAxisCount = 1,
    this.controller,
    this.staggeredTileBuilder,
    this.mainAxisSpacing = 20,
    this.crossAxisSpacing = 15,
    this.showNoData = true,
    // this.refreshItemBuilder,
    this.enableLoadMore = true,
  });

  @override
  State<StatefulWidget> createState() {
    return _SubCollectState<T>();
  }
}

class _SubCollectState<T> extends State<NormalGridView<T>>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  RefreshController _controller = RefreshController(initialRefresh: false);
  ScrollController _scrollController = ScrollController();
  final StaggeredTile? Function(int index) defaultStaggeredTileBuilder =
      (index) {
    return StaggeredTile.fit(1);
  };
  String? _error;
  List<T> _list = [];
  bool _firstLoading = true;
  int _page = 1;

  @override
  void initState() {
    _loadingGetData();
    widget.controller?._inState = this;
    _scrollController.addListener(() {
      if (widget.onScroll != null) {
        widget.onScroll!(context, -_scrollController.position.pixels);
      }
    });
    super.initState();
  }

  @override
  dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  //第一次获取数据的时候，显示加载loading
  _loadingGetData() async {
    try {
      if (mounted) {
        setState(() {
          _firstLoading = true;
        });
      }
      await _firstGetData();
    } on DioError catch (e) {
      setState(() {
        if (e.error is SocketException) {
          _error = S.of(context).network_error;
        } else {
          _error = e.message;
        }
      });
    } catch (e) {
      // _error = "$e";
      _error = S.of(context).network_error;
      debugPrintStack();
    } finally {
      setState(() {
        _firstLoading = false;
      });
    }
  }

  _firstGetData() async {
    _page = 1;
    var array = await widget.getData(1);
    if (array.length >= widget.pageSize(1)) {
      _controller.footerMode?.value = LoadStatus.idle;
    } else {
      _controller.footerMode?.value = LoadStatus.noMore;
    }
    setState(() {
      _error = null;
      _list = array;
    });
  }

  //下来获取数据
  void onRefresh() async {
    try {
      await _firstGetData();
      _controller.headerMode?.value = RefreshStatus.completed;
    } catch (e) {
      _controller.headerMode?.value = RefreshStatus.failed;
    }
  }

  //加载更多
  void onLoading() async {
    try {
      List<T> array = await widget.getData(_page + 1);
      _list += array;
      if (array.length >= widget.pageSize(_page + 1)) {
        _controller.footerMode?.value = LoadStatus.idle;
      } else {
        _controller.footerMode?.value = LoadStatus.noMore;
      }
      _page++;
      setState(() {});
    } catch (e) {
      _controller.footerMode?.value = LoadStatus.failed;
    }
  }

  Widget _showHolder() {
    if (_firstLoading) {
      return Container();
    }
    var child = widget.holder != null
        ? widget.holder!(_error != null, _error ?? "")
        : ViewStateEmptyWidget(
            message: _error != null ? "$_error" : null,
          );

    return Center(
      child: TextButton(
        child: child,
        onPressed: ClickUtils.debounce(() {
          _loadingGetData();
        }),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    Widget child = _showHolder();
    if (_firstLoading) {
      return LoadingWidget();
    } else if (_error != null) {
      return child;
    } else if (_list.length > 0 || widget.showNoData == false) {
      child = StaggeredGridView.countBuilder(
        padding: widget.padding,
        scrollDirection: Axis.vertical,
        crossAxisCount: widget.crossAxisCount,
        mainAxisSpacing: widget.mainAxisSpacing,
        crossAxisSpacing: widget.crossAxisSpacing,
        addAutomaticKeepAlives: false,
        itemCount: _list.length + (widget.header == null ? 0 : 1),
        itemBuilder: (context, index) {
          if (widget.header == null) {
            return widget.itemBuilder(context, _list[index], index);
          } else {
            if (index == 0) {
              return widget.header!(context);
            } else {
              return widget.itemBuilder(context, _list[index - 1], index - 1);
            }
          }
        },
        staggeredTileBuilder: (index) {
          var tile = widget.staggeredTileBuilder ?? defaultStaggeredTileBuilder;
          if (widget.header == null) {
            return tile(index);
          } else {
            if (index == 0) {
              return StaggeredTile.fit(widget.crossAxisCount);
            } else {
              return tile(index - 1);
            }
          }
        },
        controller: _scrollController,
      );
    }
    var refresher = SmartRefresher(
      controller: _controller,
      // header: CustomHeader(
      //   height: 110,
      //   builder: (ctx, state) {
      //     var txt = S.of(context).loading;
      //     if (state == RefreshStatus.failed) {
      //       txt = S.of(context).load_failed;
      //     } else if (state == RefreshStatus.canRefresh) {
      //       txt = S.of(context).release_to_refresh;
      //     } else if (state == RefreshStatus.idle) {
      //       txt = S.of(context).swipe_to_refresh;
      //     } else if (state == RefreshStatus.completed) {
      //       txt = S.of(context).refreshed;
      //     }

      //     Widget headerWidget = commonRefreshStateWidget(txt, Colors.white);
      //     // if (widget.refreshItemBuilder != null) {
      //     //   headerWidget = widget.refreshItemBuilder!(ctx, txt, state!);
      //     // }
      //     return headerWidget;
      //   },
      // ),
      // footer: CustomFooter(
      //   builder: (context, state) {
      //     var txt = S.of(context).loading;
      //     if (state == LoadStatus.failed) {
      //       txt = S.of(context).load_failed;
      //     } else if (state == LoadStatus.noMore) {
      //       txt = S.of(context).no_more;
      //     } else if (state == LoadStatus.idle) {
      //       txt = S.of(context).load_more;
      //     }
      //     return Container(
      //       child: Column(
      //         crossAxisAlignment: CrossAxisAlignment.center,
      //         children: [
      //           SizedBox(
      //             height: 20,
      //           ),
      //           Image.asset(
      //             "assets/icons/refresh_footer.png",
      //             width: 36,
      //             height: 32,
      //           ),
      //           Text(
      //             txt,
      //             style: TextStyle(
      //                 color: Colors.black.withOpacity(0.4), fontSize: 11),
      //           ),
      //         ],
      //       ),
      //     );
      //   },
      // ),
      onRefresh: onRefresh,
      onLoading: onLoading,
      enablePullUp: widget.enableLoadMore,
      child: child,
    );
    return Container(
      width: double.infinity,
      height: double.infinity,
      color: Colors.white,
      child: refresher,
    );
  }
}
